/**
 * 
 */
package org.jenkon.iterator;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * Implementation of a composite of {@link Iterator}. It contains many {@link Iterator} objects to
 * iterate over all.
 * 
 * @author Jens Konopka
 * 
 * @param <E> the type of {@link Iterator} value objects
 */
public class CompositeIterator<E> implements Iterator<E> {

	private Collection<Iterator<E>> iterators = new HashSet<Iterator<E>>();

	/**
	 * @param iterator the {@link Iterator} to add to {@link #iterators}.
	 */
	public void addIterator(final Iterator<E> iterator) {
		iterators.add(iterator);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.Iterator#hasNext()
	 */
	public boolean hasNext() {
		for (final Iterator<Iterator<E>> it = iterators.iterator(); it.hasNext();) {
			if (it.next().hasNext()) {
				return true;
			}
		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.Iterator#next()
	 */
	public E next() {
		for (final Iterator<Iterator<E>> it = iterators.iterator(); it.hasNext();) {
			final Iterator<E> iterator = it.next();
			if (iterator.hasNext()) {
				return iterator.next();
			}
		}
		throw new NoSuchElementException("Exhaused all iterators");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.Iterator#remove()
	 */
	public void remove() {
		throw new UnsupportedOperationException("remove() is not supported");
	}

}
